<template>
  <chat-renderer ref="renderer"
                 :danmakuAtBottom="config.danmakuAtBottom"
                 :fadeOutNum="config.fadeOutNum" :imageShowType="config.imageShowType"
                 :maxImage="config.maxImage"
                 :maxNumber="config.maxNumber" :minGiftPrice="config.minGiftPrice"
                 :minTickerPrice="config.minTickerPrice" :pinTime="config.pinTime" :showGiftInfo="config.showGiftInfo"
                 :showTranslateDanmakuOnly="config.showTranslateDanmakuOnly" :tickerAtButtom="config.tickerAtButtom"
                 :translateActive="config.translateActive" :targetLanguage="config.targetLanguage" :onlyShowTranslate="config.onlyShowTranslate"
                 :scTranslate="config.scTranslate"
  >
  </chat-renderer>
</template>

<script>
import {mergeConfig, toBool, toInt, toFloat} from '@/utils'
import * as pronunciation from '@/utils/pronunciation'
import * as chatConfig from '@/api/chatConfig'
import ChatClientTest from '@/api/chat/ChatClientTest'
import ChatClientDirect from '@/api/chat/ChatClientDirect'
import ChatClientRelay from '@/api/chat/ChatClientRelay'
import ChatRenderer from '@/components/ChatRenderer'
import * as constants from '@/components/ChatRenderer/constants'
import * as trie from '@/utils/trie'

export default {
  name: 'Room',
  components: {
    ChatRenderer
  },
  props: {
    roomId: {
      type: Number,
      default: null
    },
    strConfig: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    let styleElement = document.createElement('style')
    document.head.appendChild(styleElement)
    return {
      config: {...chatConfig.DEFAULT_CONFIG},
      chatClient: null,
      pronunciationConverter: null,
      styleElement,
      // 所有B站黄豆表情的关键词和对应的图片地址
      // 做成接口会更好维护，但是这部分B站长期不变且增加复杂度，直接写进前端了
      textEmoticons: [
        {
          "keyword": "[dog]",
          "url": "http://i0.hdslb.com/bfs/live/4428c84e694fbf4e0ef6c06e958d9352c3582740.png"
        }, {
          "keyword": "[\u82b1]",
          "url": "http://i0.hdslb.com/bfs/live/7dd2ef03e13998575e4d8a803c6e12909f94e72b.png"
        }, {
          "keyword": "[\u5999]",
          "url": "http://i0.hdslb.com/bfs/live/08f735d950a0fba267dda140673c9ab2edf6410d.png"
        }, {
          "keyword": "[\u54c7]",
          "url": "http://i0.hdslb.com/bfs/live/650c3e22c06edcbca9756365754d38952fc019c3.png"
        }, {
          "keyword": "[\u7231]",
          "url": "http://i0.hdslb.com/bfs/live/1daaa5d284dafaa16c51409447da851ff1ec557f.png"
        }, {
          "keyword": "[\u624b\u673a]",
          "url": "http://i0.hdslb.com/bfs/live/b159f90431148a973824f596288e7ad6a8db014b.png"
        }, {
          "keyword": "[\u6487\u5634]",
          "url": "http://i0.hdslb.com/bfs/live/4255ce6ed5d15b60311728a803d03dd9a24366b2.png"
        }, {
          "keyword": "[\u59d4\u5c48]",
          "url": "http://i0.hdslb.com/bfs/live/69312e99a00d1db2de34ef2db9220c5686643a3f.png"
        }, {
          "keyword": "[\u6293\u72c2]",
          "url": "http://i0.hdslb.com/bfs/live/a7feb260bb5b15f97d7119b444fc698e82516b9f.png"
        }, {
          "keyword": "[\u6bd4\u5fc3]",
          "url": "http://i0.hdslb.com/bfs/live/4e029593562283f00d39b99e0557878c4199c71d.png"
        }, {
          "keyword": "[\u8d5e]",
          "url": "http://i0.hdslb.com/bfs/live/2dd666d3651bafe8683acf770b7f4163a5f49809.png"
        }, {
          "keyword": "[\u6ed1\u7a3d]",
          "url": "http://i0.hdslb.com/bfs/live/8624fd172037573c8600b2597e3731ef0e5ea983.png"
        }, {
          "keyword": "[\u5403\u74dc]",
          "url": "http://i0.hdslb.com/bfs/live/ffb53c252b085d042173379ac724694ce3196194.png"
        }, {
          "keyword": "[\u7b11\u54ed]",
          "url": "http://i0.hdslb.com/bfs/live/c5436c6806c32b28d471bb23d42f0f8f164a187a.png"
        }, {
          "keyword": "[\u6342\u8138]",
          "url": "http://i0.hdslb.com/bfs/live/e6073c6849f735ae6cb7af3a20ff7dcec962b4c5.png"
        }, {
          "keyword": "[\u559d\u5f69]",
          "url": "http://i0.hdslb.com/bfs/live/b51824125d09923a4ca064f0c0b49fc97d3fab79.png"
        }, {
          "keyword": "[\u5077\u7b11]",
          "url": "http://i0.hdslb.com/bfs/live/e2ba16f947a23179cdc00420b71cc1d627d8ae25.png"
        }, {
          "keyword": "[\u5927\u7b11]",
          "url": "http://i0.hdslb.com/bfs/live/e2589d086df0db8a7b5ca2b1273c02d31d4433d4.png"
        }, {
          "keyword": "[\u60ca\u559c]",
          "url": "http://i0.hdslb.com/bfs/live/9c75761c5b6e1ff59b29577deb8e6ad996b86bd7.png"
        }, {
          "keyword": "[\u50b2\u5a07]",
          "url": "http://i0.hdslb.com/bfs/live/b5b44f099059a1bafb2c2722cfe9a6f62c1dc531.png"
        }, {
          "keyword": "[\u75bc]",
          "url": "http://i0.hdslb.com/bfs/live/492b10d03545b7863919033db7d1ae3ef342df2f.png"
        }, {
          "keyword": "[\u5413]",
          "url": "http://i0.hdslb.com/bfs/live/c6bed64ffb78c97c93a83fbd22f6fdf951400f31.png"
        }, {
          "keyword": "[\u9634\u9669]",
          "url": "http://i0.hdslb.com/bfs/live/a4df45c035b0ca0c58f162b5fb5058cf273d0d09.png"
        }, {
          "keyword": "[\u60ca\u8bb6]",
          "url": "http://i0.hdslb.com/bfs/live/bc26f29f62340091737c82109b8b91f32e6675ad.png"
        }, {
          "keyword": "[\u751f\u75c5]",
          "url": "http://i0.hdslb.com/bfs/live/84c92239591e5ece0f986c75a39050a5c61c803c.png"
        }, {
          "keyword": "[\u5618]",
          "url": "http://i0.hdslb.com/bfs/live/b6226219384befa5da1d437cb2ff4ba06c303844.png"
        }, {
          "keyword": "[\u5978\u7b11]",
          "url": "http://i0.hdslb.com/bfs/live/5935e6a4103d024955f749d428311f39e120a58a.png"
        }, {
          "keyword": "[\u56e7]",
          "url": "http://i0.hdslb.com/bfs/live/204413d3cf330e122230dcc99d29056f2a60e6f2.png"
        }, {
          "keyword": "[\u6342\u81382]",
          "url": "http://i0.hdslb.com/bfs/live/a2ad0cc7e390a303f6d243821479452d31902a5f.png"
        }, {
          "keyword": "[\u51fa\u7a8d]",
          "url": "http://i0.hdslb.com/bfs/live/bb8e95fa54512ffea07023ea4f2abee4a163e7a0.png"
        }, {
          "keyword": "[\u5410\u4e86\u554a]",
          "url": "http://i0.hdslb.com/bfs/live/2b6b4cc33be42c3257dc1f6ef3a39d666b6b4b1a.png"
        }, {
          "keyword": "[\u9f3b\u5b50]",
          "url": "http://i0.hdslb.com/bfs/live/f4ed20a70d0cb85a22c0c59c628aedfe30566b37.png"
        }, {
          "keyword": "[\u8c03\u76ae]",
          "url": "http://i0.hdslb.com/bfs/live/84fe12ecde5d3875e1090d83ac9027cb7d7fba9f.png"
        }, {
          "keyword": "[\u9178]",
          "url": "http://i0.hdslb.com/bfs/live/98fd92c6115b0d305f544b209c78ec322e4bb4ff.png"
        }, {
          "keyword": "[\u51b7]",
          "url": "http://i0.hdslb.com/bfs/live/b804118a1bdb8f3bec67d9b108d5ade6e3aa93a9.png"
        }, {
          "keyword": "[OK]",
          "url": "http://i0.hdslb.com/bfs/live/86268b09e35fbe4215815a28ef3cf25ec71c124f.png"
        }, {
          "keyword": "[\u5fae\u7b11]",
          "url": "http://i0.hdslb.com/bfs/live/f605dd8229fa0115e57d2f16cb019da28545452b.png"
        }, {
          "keyword": "[\u85cf\u72d0]",
          "url": "http://i0.hdslb.com/bfs/live/05ef7849e7313e9c32887df922613a7c1ad27f12.png"
        }, {
          "keyword": "[\u9f87\u7259]",
          "url": "http://i0.hdslb.com/bfs/live/8b99266ea7b9e86cf9d25c3d1151d80c5ba5c9a1.png"
        }, {
          "keyword": "[\u9632\u62a4]",
          "url": "http://i0.hdslb.com/bfs/live/17435e60dcc28ce306762103a2a646046ff10b0a.png"
        }, {
          "keyword": "[\u7b11]",
          "url": "http://i0.hdslb.com/bfs/live/a91a27f83c38b5576f4cd08d4e11a2880de78918.png"
        }, {
          "keyword": "[\u4e00\u822c]",
          "url": "http://i0.hdslb.com/bfs/live/8d436de0c3701d87e4ca9c1be01c01b199ac198e.png"
        }, {
          "keyword": "[\u5acc\u5f03]",
          "url": "http://i0.hdslb.com/bfs/live/c409425ba1ad2c6534f0df7de350ba83a9c949e5.png"
        }, {
          "keyword": "[\u65e0\u8bed]",
          "url": "http://i0.hdslb.com/bfs/live/4781a77be9c8f0d4658274eb4e3012c47a159f23.png"
        }, {
          "keyword": "[\u54c8\u6b20]",
          "url": "http://i0.hdslb.com/bfs/live/6e496946725cd66e7ff1b53021bf1cc0fc240288.png"
        }, {
          "keyword": "[\u53ef\u601c]",
          "url": "http://i0.hdslb.com/bfs/live/8e88e6a137463703e96d4f27629f878efa323456.png"
        }, {
          "keyword": "[\u6b6a\u5634\u7b11]",
          "url": "http://i0.hdslb.com/bfs/live/bea1f0497888f3e9056d3ce14ba452885a485c02.png"
        }, {
          "keyword": "[\u4eb2\u4eb2]",
          "url": "http://i0.hdslb.com/bfs/live/10662d9c0d6ddb3203ecf50e77788b959d4d1928.png"
        }, {
          "keyword": "[\u95ee\u53f7]",
          "url": "http://i0.hdslb.com/bfs/live/a0c456b6d9e3187399327828a9783901323bfdb5.png"
        }, {
          "keyword": "[\u6ce2\u5409]",
          "url": "http://i0.hdslb.com/bfs/live/57dee478868ed9f1ce3cf25a36bc50bde489c404.png"
        }, {
          "keyword": "[OH]",
          "url": "http://i0.hdslb.com/bfs/live/0d5123cddf389302df6f605087189fd10919dc3c.png"
        }, {
          "keyword": "[\u518d\u89c1]",
          "url": "http://i0.hdslb.com/bfs/live/f408e2af700adcc2baeca15510ef620bed8d4c43.png"
        }, {
          "keyword": "[\u767d\u773c]",
          "url": "http://i0.hdslb.com/bfs/live/7fa907ae85fa6327a0466e123aee1ac32d7c85f7.png"
        }, {
          "keyword": "[\u9f13\u638c]",
          "url": "http://i0.hdslb.com/bfs/live/d581d0bc30c8f9712b46ec02303579840c72c42d.png"
        }, {
          "keyword": "[\u5927\u54ed]",
          "url": "http://i0.hdslb.com/bfs/live/816402551e6ce30d08b37a917f76dea8851fe529.png"
        }, {
          "keyword": "[\u5446]",
          "url": "http://i0.hdslb.com/bfs/live/179c7e2d232cd74f30b672e12fc728f8f62be9ec.png"
        }, {
          "keyword": "[\u6d41\u6c57]",
          "url": "http://i0.hdslb.com/bfs/live/b00e2e02904096377061ec5f93bf0dd3321f1964.png"
        }, {
          "keyword": "[\u751f\u6c14]",
          "url": "http://i0.hdslb.com/bfs/live/2c69dad2e5c0f72f01b92746bc9d148aee1993b2.png"
        }, {
          "keyword": "[\u52a0\u6cb9]",
          "url": "http://i0.hdslb.com/bfs/live/fbc3c8bc4152a65bbf4a9fd5a5d27710fbff2119.png"
        }, {
          "keyword": "[\u5bb3\u7f9e]",
          "url": "http://i0.hdslb.com/bfs/live/d8ce9b05c0e40cec61a15ba1979c8517edd270bf.png"
        }, {
          "keyword": "[\u864e\u5e74]",
          "url": "http://i0.hdslb.com/bfs/live/a51af0d7d9e60ce24f139c468a3853f9ba9bb184.png"
        }, {
          "keyword": "[doge2]",
          "url": "http://i0.hdslb.com/bfs/live/f547cc853cf43e70f1e39095d9b3b5ac1bf70a8d.png"
        }, {
          "keyword": "[\u91d1\u94b1\u8c79]",
          "url": "http://i0.hdslb.com/bfs/live/b6e8131897a9a718ee280f2510bfa92f1d84429b.png"
        }, {
          "keyword": "[\u74dc\u5b50]",
          "url": "http://i0.hdslb.com/bfs/live/fd35718ac5a278fd05fe5287ebd41de40a59259d.png"
        }, {
          "keyword": "[\u58a8\u955c]",
          "url": "http://i0.hdslb.com/bfs/live/5e01c237642c8b662a69e21b8e0fbe6e7dbc2aa1.png"
        }, {
          "keyword": "[\u96be\u8fc7]",
          "url": "http://i0.hdslb.com/bfs/live/5776481e380648c0fb3d4ad6173475f69f1ce149.png"
        }, {
          "keyword": "[\u62b1\u62b1]",
          "url": "http://i0.hdslb.com/bfs/live/abddb0b621b389fc8c2322b1cfcf122d8936ba91.png"
        }, {
          "keyword": "[\u8dea\u4e86]",
          "url": "http://i0.hdslb.com/bfs/live/4f2155b108047d60c1fa9dccdc4d7abba18379a0.png"
        }, {
          "keyword": "[\u644a\u624b]",
          "url": "http://i0.hdslb.com/bfs/live/1e0a2baf088a34d56e2cc226b2de36a5f8d6c926.png"
        }, {
          "keyword": "[\u70ed]",
          "url": "http://i0.hdslb.com/bfs/live/6df760280b17a6cbac8c1874d357298f982ba4cf.png"
        }, {
          "keyword": "[\u4e09\u661f\u5806]",
          "url": "http://i0.hdslb.com/bfs/live/0a1ab3f0f2f2e29de35c702ac1ecfec7f90e325d.png"
        }, {
          "keyword": "[\u9f20]",
          "url": "http://i0.hdslb.com/bfs/live/98f842994035505c728e32e32045d649e371ecd6.png"
        }, {
          "keyword": "[\u6c64\u5706]",
          "url": "http://i0.hdslb.com/bfs/live/23ae12d3a71b9d7a22c8773343969fcbb94b20d0.png"
        }, {
          "keyword": "[\u6cfc\u6c34]",
          "url": "http://i0.hdslb.com/bfs/live/29533893115c4609a4af336f49060ea13173ca78.png"
        }, {
          "keyword": "[\u9b3c\u9b42]",
          "url": "http://i0.hdslb.com/bfs/live/5d86d55ba9a2f99856b523d8311cf75cfdcccdbc.png"
        }, {
          "keyword": "[\u4e0d\u884c]",
          "url": "http://i0.hdslb.com/bfs/live/607f74ccf5eec7d2b17d91b9bb36be61a5dd196b.png"
        }, {
          "keyword": "[\u54cd\u6307]",
          "url": "http://i0.hdslb.com/bfs/live/3b2fedf09b0ac79679b5a47f5eb3e8a38e702387.png"
        }, {
          "keyword": "[\u725b]",
          "url": "http://i0.hdslb.com/bfs/live/5e61223561203c50340b4c9b41ba7e4b05e48ae2.png"
        }, {
          "keyword": "[\u4fdd\u4f51]",
          "url": "http://i0.hdslb.com/bfs/live/241b13adb4933e38b7ea6f5204e0648725e76fbf.png"
        }, {
          "keyword": "[\u62b1\u62f3]",
          "url": "http://i0.hdslb.com/bfs/live/3f170894dd08827ee293afcb5a3d2b60aecdb5b1.png"
        }, {
          "keyword": "[\u7ed9\u529b]",
          "url": "http://i0.hdslb.com/bfs/live/d1ba5f4c54332a21ed2ca0dcecaedd2add587839.png"
        }, {"keyword": "[\u8036]", "url": "http://i0.hdslb.com/bfs/live/eb2d84ba623e2335a48f73fb5bef87bcf53c1239.png"}],
      user_data: {
        "code": "",
        "mid": "",
        "timestamp": "",
        "sign": ""
      },
      paidSkinList: null,
    }
  },
  computed: {
    blockKeywords() {
      return this.config.blockKeywords.split('\n').filter(val => val)
    },
    blockUsers() {
      return this.config.blockUsers.split('\n').filter(val => val)
    },
    emoticonsTrie() {
      let res = new trie.Trie()
      for (let emoticons of this.textEmoticons) {
        if (emoticons.keyword !== '' && emoticons.url !== '') {
          res.set(emoticons.keyword, emoticons)
        }
      }
      return res
    },
    // 皮肤列表，合并购买dlc的皮肤
    skinList() {
      let defaultSkinList = [
        {
          "url": "",
          "id": "none",
          "name": this.$t("home.skinList['none']"),
          "thumb": ""
        },
        {
          "url": "https://i1.xuehusang.cn/openlivechat-css/openlivechat.css",
          "id": "openlivechat",
          "author": "兔宝的神奇口袋",
          "name": this.$t("home.skinList['openlivechat']"),
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/openlivechat.jpg"
        },
        {
          "id": "default",
          "url": "https://i1.xuehusang.cn/openlivechat-css/default.css",
          "name": this.$t("home.skinList['default']"),
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/default.jpg"
        },
        {
          "id": "1125-candy-game-all-in",
          "url": "https://i1.xuehusang.cn/openlivechat-css/1125-candy-game-all-in.css",
          "name": this.$t("home.skinList['1125-candy-game-all-in']"),
          "author": "兔宝的神奇口袋",
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/1125-candy-game-all-in.jpg"
        },
        {
          "url": "https://i1.xuehusang.cn/openlivechat-css/A45%E9%AD%94%E5%A5%B3%E8%8A%B1%E5%AB%81light.css",
          "id": "monvhuajia-light",
          "name": this.$t("home.skinList['monvhuajia-light']"),
          "author": "槐夏虫眠",
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/monvhuajia-light.jpg"
        },
        {
          "url": "https://i1.xuehusang.cn/openlivechat-css/A45%E9%AD%94%E5%A5%B3%E8%8A%B1%E5%AB%81night.css",
          "id": "monvhuajia-night",
          "name": this.$t("home.skinList['monvhuajia-night']"),
          "author": "槐夏虫眠",
          "thumb": "https://i1.xuehusang.cn/openlivechat-css/thumbnail/monvhuajia-night.jpg"
        }
      ]
      return defaultSkinList.concat(this.paidSkinList)
    }
  },
  mounted() {
    if (document.visibilityState === 'visible') {
      this.init()
    } else {
      // 当前窗口不可见，延迟到可见时加载，防止OBS中一次并发太多请求（OBS中浏览器不可见时也会加载网页，除非显式设置）
      // 这么设计师因为很多用户obs里不同场景下不止添加一个弹幕姬，超过5个会直接导致连接失败
      document.addEventListener('visibilitychange', this.onVisibilityChange)
    }
  },
  // 从来没能有用的关闭前停止场次，涉及vue生命周期和前代开发者的历史遗留问题
  beforeDestroy() {
    document.removeEventListener('visibilitychange', this.onVisibilityChange)
    if (this.chatClient) {
      this.chatClient.stop()
    }
  },
  methods: {
    init() {
      this.user_data = {
        "code": this.$route.query.Code,
        "mid": this.$route.query.Mid,
        "timestamp": this.$route.query.Timestamp,
        "sign": this.$route.query.CodeSign
      }
      this.initConfig()
      this.initChatClient()
      if (this.config.giftUsernamePronunciation !== '') {
        this.pronunciationConverter = new pronunciation.PronunciationConverter()
        this.pronunciationConverter.loadDict(this.config.giftUsernamePronunciation)
      }
    },
    onVisibilityChange() {
      if (document.visibilityState !== 'visible') {
        return
      }
      document.removeEventListener('visibilitychange', this.onVisibilityChange)
      this.init()
    },
    initConfig() {
      // console.log("初始化config")
      //* 留空的使用上次预设值
      let cfg = {...chatConfig.getLocalConfig()}
      for (let i in this.strConfig) {
        if (this.strConfig[i] !== '') {
          cfg[i] = this.strConfig[i]
        }
      }
      //* 若上次预设值有留空，则使用默认值
      cfg = mergeConfig(cfg, chatConfig.DEFAULT_CONFIG)
      cfg.stylesheet = (cfg.stylesheet !== "") ? cfg.stylesheet : chatConfig.DEFAULT_CONFIG.stylesheet
      cfg.minGiftPrice = toFloat(cfg.minGiftPrice, chatConfig.DEFAULT_CONFIG.minGiftPrice)
      cfg.minTickerPrice = toFloat(cfg.minTickerPrice, chatConfig.DEFAULT_CONFIG.minTickerPrice)

      cfg.showDanmaku = toBool(cfg.showDanmaku)
      cfg.showSuperchat = toBool(cfg.showSuperchat)
      cfg.showNewMember = toBool(cfg.showNewMember)
      cfg.showGift = toBool(cfg.showGift)
      cfg.showGiftInfo = toBool(cfg.showGiftInfo)
      cfg.showLike = toBool(cfg.showLike)

      cfg.mergeSimilarDanmaku = toBool(cfg.mergeSimilarDanmaku)
      cfg.mergeGift = toBool(cfg.mergeGift)

      cfg.danmakuAtBottom = toBool(cfg.danmakuAtBottom)
      cfg.tickerAtButtom = toBool(cfg.tickerAtButtom)
      cfg.userNameBlur = toBool(cfg.userNameBlur)

      cfg.showTranslateDanmakuOnly = toBool(cfg.showTranslateDanmakuOnly)
      cfg.translationSign = cfg.translationSign.toString()

      cfg.maxNumber = toInt(cfg.maxNumber, chatConfig.DEFAULT_CONFIG.maxNumber)
      cfg.fadeOutNum = toInt(cfg.fadeOutNum, chatConfig.DEFAULT_CONFIG.fadeOutNum)
      cfg.pinTime = toInt(cfg.pinTime, chatConfig.DEFAULT_CONFIG.pinTime)

      cfg.imageShowType = toInt(cfg.imageShowType, chatConfig.DEFAULT_CONFIG.imageShowType)
      cfg.maxImage = toInt(cfg.maxImage, chatConfig.DEFAULT_CONFIG.maxImage)

      cfg.blockGiftDanmaku = toBool(cfg.blockGiftDanmaku)
      cfg.blockLevel = toInt(cfg.blockLevel, chatConfig.DEFAULT_CONFIG.blockLevel)
      cfg.blockNewbie = toBool(cfg.blockNewbie)
      cfg.blockNotMobileVerified = toBool(cfg.blockNotMobileVerified)
      cfg.blockMedalLevel = toInt(cfg.blockMedalLevel, chatConfig.DEFAULT_CONFIG.blockMedalLevel)
      cfg.relayMessagesByServer = toBool(cfg.relayMessagesByServer)
      cfg.autoTranslate = toBool(cfg.autoTranslate)

      cfg.minDanmakuInterval = toInt(cfg.minDanmakuInterval, chatConfig.DEFAULT_CONFIG.minDanmakuInterval)
      cfg.maxDanmakuInterval = toInt(cfg.maxDanmakuInterval, chatConfig.DEFAULT_CONFIG.maxDanmakuInterval)
      cfg.translateActive = toBool(cfg.translateActive)
      cfg.targetLanguage = cfg.targetLanguage.toString()
      cfg.onlyShowTranslate = toBool(cfg.onlyShowTranslate)
      cfg.scTranslate = toBool(cfg.scTranslate)


      this.config = cfg
    },
    initChatClient() {
      if (this.roomId === null) {
        this.chatClient = new ChatClientTest(this.config.minDanmakuInterval, this.config.maxDanmakuInterval)
      } else {
        if (!this.config.relayMessagesByServer) {
          this.chatClient = new ChatClientDirect(this.user_data.code, this.user_data.sign, this.user_data.timestamp, this.user_data.mid, this.config.translateActive, this.config.scTranslate, this.config.targetLanguage)
        } else {
          this.chatClient = new ChatClientRelay(this.roomId, this.config.autoTranslate)
        }
      }
      this.chatClient.onAddText = this.onAddText
      this.chatClient.onAddLike = this.onAddLike
      this.chatClient.onAddGift = this.onAddGift
      this.chatClient.onAddMember = this.onAddMember
      this.chatClient.onAddSuperChat = this.onAddSuperChat
      this.chatClient.onDelSuperChat = this.onDelSuperChat
      this.chatClient.onUpdateTranslation = this.onUpdateTranslation
      this.chatClient.onPaidSkinList = this.onAddPaidSkinList
      this.chatClient.onAddStatus = this.onAddStatus
      this.chatClient.start()
      setTimeout(this.checkInitStatus, 3000)
    },
    start() {
      if(this.chatClient.start())
      this.chatClient.start()
    },
    stop() {
      this.chatClient.stop()
    },
    onAddStatus(data) {
      if (data === true) {
        this.$message.error({
          message: `心跳保持失败，弹幕即将中断，请刷新`,
          duration: '0'
        })
      }
    },

    onAddText(data) {
      let uname = (this.config.userBlur === true) ? `${data.authorName[0]}***` : data.authorName
      if (!this.config.showDanmaku || !this.filterTextMessage(data) || this.mergeSimilarText(data.content)) {
        // console.log("收到一般消息弹幕，但：是否显示弹幕为" + this.config.showDanmaku + "，是否合并弹幕为" + this.config.mergeSimilarDanmaku)
        return
      }
      if (this.config.showTranslateDanmakuOnly) {
        let content_str = data.content
        if (content_str.charAt(0) != this.config.translationSign) {
          // console.log("只显示以“"+ this.config.translationSign +"”开头的翻译弹幕")
          return
        } else {
          data.content = "翻译：" + content_str.substring(1)
        }
      }
      let message = {
        id: data.id,
        type: constants.MESSAGE_TYPE_TEXT,
        avatarUrl: data.avatarUrl,
        time: new Date(data.timestamp * 1000),
        authorName: uname,
        authorType: data.authorType,
        content: data.content,
        richContent: this.getRichContent(data),
        emoticon: data.emoticon,
        privilegeType: data.privilegeType,
        medalName: data.medalName,
        medalLevel: data.medalLevel,
        isFanGroup: data.isFanGroup,
        repeated: 1,
        translation: data.translation,
        richTranslate: this.getRichTranslate(data)
      }
      // 判断是否是iframe，忽略报错
      if (this.$refs.renderer) {
        this.$refs.renderer.addMessage(message)
      }
    },
    onAddLike(data) {
      if (!this.config.showLike) {
        return
      }
      if (this.mergeSimilarLike(data.authorName, data.likeCount)) {
        return
      }
      let uname = (this.config.userBlur === true) ? `${data.authorName[0]}***` : data.authorName
      let message = {
        id: data.id,
        type: constants.MESSAGE_TYPE_TEXT,
        avatarUrl: data.avatarUrl,
        time: new Date(data.timestamp * 1000),
        authorName: uname,
        authorType: data.authorType,
        content: data.content,
        likeCount: data.likeCount,
        richContent: this.getRichContent(data),
        emoticon: data.emoticon,
        privilegeType: data.privilegeType,
        medalName: data.medalName,
        medalLevel: data.medalLevel,
        isFanGroup: data.isFanGroup,
        repeated: 1,
        translation: data.translation
      }
      // 判断是否是iframe，忽略报错
      if (this.$refs.renderer) {
        this.$refs.renderer.addMessage(message)
      }
    },
    onAddGift(data) {
      if (!this.config.showGift) {
        // console.log("收到礼物，但是否显示礼物为" + this.config.showGift)
        return
      }
      if (this.config.showTranslateDanmakuOnly) {
        // console.log("只显示以“"+ this.config.translationSign +"”开头的翻译弹幕")
        return
      }
      let uname = (this.config.userBlur === true) ? `${data.authorName[0]}***` : data.authorName

      let price = (data.totalCoin / 1000)
      if (this.mergeSimilarGift(data.authorName, price, data.giftName, data.num)) {
        return
      }
      // 银瓜子礼物不丢人
      // if (price < this.config.minGiftPrice) {
      //  return
      // }

      let message = {
        id: data.id,
        type: constants.MESSAGE_TYPE_GIFT,
        avatarUrl: data.avatarUrl,
        time: new Date(data.timestamp * 1000),
        authorName: uname,
        authorNamePronunciation: this.getPronunciation(data.authorName),
        price: price,
        giftName: data.giftName,
        num: data.num
      }
      // 判断是否是iframe，忽略报错
      if (this.$refs.renderer) {
        this.$refs.renderer.addMessage(message)
      }
    },
    onAddMember(data) {
      if (!this.config.showNewMember || !this.filterNewMemberMessage(data)) {
        // console.log("收到上舰，但是否显示上舰信息为" + this.config.showNewMember)
        return
      }
      if (this.config.showTranslateDanmakuOnly) {
        // console.log("只显示以“"+ this.config.translationSign +"”开头的翻译弹幕")
        return
      }
      let uname = (this.config.userBlur === true) ? `${data.authorName[0]}***` : data.authorName
      let price = data.privilegeType == 3 ? 198 : data.privilegeType == 2 ? 1998 : 19998
      let message = {
        id: data.id,
        type: constants.MESSAGE_TYPE_MEMBER,
        avatarUrl: data.avatarUrl,
        time: new Date(data.timestamp * 1000),
        authorName: uname,
        authorNamePronunciation: this.getPronunciation(data.authorName),
        privilegeType: data.privilegeType,
        title: data.authorName,
        price: price
      }
      // 判断是否是iframe，忽略报错
      if (this.$refs.renderer) {
        this.$refs.renderer.addMessage(message)
      }
    },
    onAddSuperChat(data) {
      if (!this.config.showSuperchat || !this.filterSuperChatMessage(data)) {
        // console.log("收到打赏(醒目留言SC)，但显示打赏(醒目留言SC)为" + this.config.showSuperchat)
        return
      }
      if (data.price < this.config.minGiftPrice) { // 丢人
        // console.log("打赏小于最低打赏金额，不以显示")
        return
      }
      if (this.config.showTranslateDanmakuOnly) {
        // console.log("只显示以“"+ this.config.translationSign +"”开头的翻译弹幕")
        return
      }
      let uname = (this.config.userBlur === true) ? `${data.authorName[0]}***` : data.authorName

      let message = {
        id: data.id,
        type: constants.MESSAGE_TYPE_SUPER_CHAT,
        avatarUrl: data.avatarUrl,
        authorName: uname,
        authorNamePronunciation: this.getPronunciation(data.authorName),
        price: data.price,
        time: new Date(data.timestamp * 1000),
        content: data.content.trim(),
        translation: data.translation,
        severTranslation: data.severTranslation
      }
      // 判断是否是iframe，忽略报错
      if (this.$refs.renderer) {
        this.$refs.renderer.addMessage(message)
      }
    },
    onDelSuperChat(data) {
      for (let id of data.ids) {
        // 判断是否是iframe，忽略报错
        // 判断是否是iframe，忽略报错
        if (this.$refs.renderer) {
          this.$refs.renderer.delMessage(id)
        }
      }
    },
    onAddPaidSkinList(data) {
      this.paidSkinList = data
    },
    onUpdateTranslation(data) {
      if (!this.config.autoTranslate) {
        return
      }
      this.$refs.renderer.updateMessage(data.id, {translation: data.translation})
    },

    filterTextMessage(data) {
      if (this.config.blockGiftDanmaku && data.isGiftDanmaku) {
        return false
      } else if (this.config.blockLevel > 0 && data.authorLevel < this.config.blockLevel) {
        return false
      } else if (this.config.blockNewbie && data.isNewbie) {
        return false
      } else if (this.config.blockNotMobileVerified && !data.isMobileVerified) {
        return false
      } else if (this.config.blockMedalLevel > 0 && data.medalLevel < this.config.blockMedalLevel) {
        return false
      }
      return this.filterSuperChatMessage(data)
    },
    filterSuperChatMessage(data) {
      for (let keyword of this.blockKeywords) {
        if (data.content.indexOf(keyword) !== -1) {
          return false
        }
      }
      return this.filterNewMemberMessage(data)
    },
    filterNewMemberMessage(data) {
      for (let user of this.blockUsers) {
        if (data.authorName === user) {
          return false
        }
      }
      return true
    },
    mergeSimilarText(content) {
      if (!this.config.mergeSimilarDanmaku) {
        return false
      }
      return this.$refs.renderer.mergeSimilarText(content)
    },
    mergeSimilarGift(authorName, price, giftName, num) {
      if (!this.config.mergeGift) {
        return false
      }
      // 补充判空机制
      if (this.$refs.renderer) {
        return this.$refs.renderer.mergeSimilarGift(authorName, price, giftName, num)
      }
    },
    mergeSimilarLike(authorName, likeCount) {
      // 补充判空机制
      if (this.$refs.renderer) {
        return this.$refs.renderer.mergeSimilarLike(authorName, likeCount)
      }
    },
    getPronunciation(text) {
      if (this.pronunciationConverter === null) {
        return ''
      }
      return this.pronunciationConverter.getPronunciation(text)
    },
    applySkin(skin_id) {
      try {
        const pick_skin = this.skinList.find(s => s.id === skin_id)
        this.styleElement.innerText = "@import url('" + pick_skin['url'] + "');"
      } catch (e) {
      }
    },
    checkInitStatus() {
      if (this.chatClient.status === false) {
        this.$message.error({
          message: `加载弹幕姬失败，报错:${this.chatClient.statusDesc}`,
          duration: '0'
        })
      } else {
        // 根据plug_env检测是否是直播姬开平插件用户
        if (this.$route.query.plug_env == 0) {
          this.applySkin("openlivechat")
          this.$message({message: '检测到直播姬插件连接，默认加载皮肤：糖果色'})
        } else {
          const checkSkinStatus = setInterval(() => {
            if(this.chatClient.initStartLink === true) {
              this.applySkin(this.$route.query.skin)
              clearInterval(checkSkinStatus)
            }
          }, 500)
        }
        // 提示用户已加载
        this.$message({
          message: '加载房间成功',
          duration: '500'
        })
      }
    },
    // 判断弹幕是否含[xxx]的emoji格式
    isContentContainEmojiChart(content) {
      return /\[.*?]/.test(content);
    },
    getRichContent(data) {
      let richContent = []

      // B站官方表情
      if (data.emoticon !== null) {
        richContent.push({
          type: constants.CONTENT_TYPE_IMAGE,
          text: data.content,
          url: data.emoticon
        })
        return richContent
      }

      // 没有文本表情，只能是纯文本
      if (this.isContentContainEmojiChart(data.content) === false ) {
        richContent.push({
          type: constants.CONTENT_TYPE_TEXT,
          text: data.content
        })
        return richContent
      }

      // 可能含有文本表情，需要解析
      let emoticonsTrie = this.emoticonsTrie
      let startPos = 0
      let pos = 0
      while (pos < data.content.length) {
        let remainContent = data.content.substring(pos)
        let matchEmoticon = emoticonsTrie.lazyMatch(remainContent)
        if (matchEmoticon === null) {
          pos++
          continue
        }

        // 加入之前的文本
        if (pos !== startPos) {
          richContent.push({
            type: constants.CONTENT_TYPE_TEXT,
            text: data.content.slice(startPos, pos)
          })
        }

        // 加入表情
        richContent.push({
          type: constants.CONTENT_TYPE_IMAGE,
          text: matchEmoticon.keyword,
          url: matchEmoticon.url
        })
        pos += matchEmoticon.keyword.length
        startPos = pos
      }
      // 加入尾部的文本
      if (pos !== startPos) {
        richContent.push({
          type: constants.CONTENT_TYPE_TEXT,
          text: data.content.slice(startPos, pos)
        })
      }

      return richContent
    },
    getRichTranslate(data) {
      let richTranslate = []
      if (this.isContentContainEmojiChart(data.translation) === false) {
        richTranslate.push({
          type: constants.CONTENT_TYPE_TEXT,
          text: data.translation
        })
        return richTranslate
      }
      // 含有文本表情，需要解析
      let emoticonsTrie = this.emoticonsTrie
      let startPos = 0
      let pos = 0

      while (pos < data.translation.length) {
        let remainContent = data.translation.substring(pos)
        let matchEmoticon = emoticonsTrie.lazyMatch(remainContent)
        if (matchEmoticon === null) {
          pos++
          continue
        }

        // 加入之前的文本
        if (pos !== startPos) {
          richTranslate.push({
            type: constants.CONTENT_TYPE_TEXT,
            text: data.translation.slice(startPos, pos)
          })
        }

        // 加入表情
        richTranslate.push({
          type: constants.CONTENT_TYPE_IMAGE,
          text: matchEmoticon.keyword,
          url: matchEmoticon.url
        })
        pos += matchEmoticon.keyword.length
        startPos = pos
      }
      // 加入尾部的文本
      if (pos !== startPos) {
        richTranslate.push({
          type: constants.CONTENT_TYPE_TEXT,
          text: data.translation.slice(startPos, pos)
        })
      }
      // console.log(richTranslate)
      return richTranslate
    }
  }
}
</script>
